//
//  LHOAuthController.swift
//  sina_weibo
//
//  Created by 刘刘海强 on 16/5/11.
//  Copyright © 2016年 chuanzhi. All rights reserved.
//

import UIKit
import AFNetworking
import SVProgressHUD

let WeiboAppKey = "2177339420"

let WeiboRedirect_Uri = "http://www.itcast.cn"

let weiboAppSecret = "7dd8c185dee4fcfe65c96538f61a4ad9"

class LHOAuthController: UIViewController {
    
    private lazy var webView: UIWebView = UIWebView()
    
    override func loadView() {
        
        webView.delegate = self
        view = webView
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        setupNavUI()
        let url = "https://api.weibo.com/oauth2/authorize?client_id=\(WeiboAppKey)&redirect_uri=\(WeiboRedirect_Uri)"
        
        let request = NSURLRequest(URL: NSURL(string: url)!)
        
        webView.loadRequest(request)
        
        
        
    }
    
    private func setupNavUI() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", fontSize: 15, target: self, action: "cancelAction")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", fontSize: 15, target: self, action: "autoFillAction")
        navigationItem.title = "微博登录"
    }
    
    @objc private func cancelAction() {
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    @objc private func autoFillAction() {
        webView.stringByEvaluatingJavaScriptFromString("document.getElementById('userId').value = '18612395941';document.getElementById('passwd').value = 'Lhq123456'")
    }


}


extension LHOAuthController: UIWebViewDelegate {
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        //每次有新的网络请求时，都会打印请求的URL
//        print("----->\(request)")
        guard let url = request.URL else {
            return false
        }
        
        if !url.absoluteString.hasPrefix(WeiboRedirect_Uri) {
            return true
        }
        
        //点击授权后请求的URL为"http://www.itcast.cn/?code=54752efd0d04cb9fc489a7f39da4fc47"
        //query方法的作用是获得请求URL中的参数，即问号后面的内容code=54752efd0d04cb9fc489a7f39da4fc47
        if let query = url.query where query.hasPrefix("code=") {
            //得到AccessToken
            let code = query.substringFromIndex("code=".endIndex)
            LHUserAccountModel.sharedUserAccount.requestAccessToken(code, complete: { (isSuccess) -> () in
                if isSuccess {
                    self.dismissViewControllerAnimated(false, completion: { () -> Void in
                        NSNotificationCenter.defaultCenter().postNotificationName(SwitchRootVCNotification, object: self)
                    })
                }else{
                    SVProgressHUD.showErrorWithStatus("登录失败")
                }
            })
            
        } else {
            dismissViewControllerAnimated(true, completion: nil)
        }
        
        return false
    }
    
    //开始加载时调用
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    //加载完成时调用
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    //加载失败时加载
    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
        SVProgressHUD.dismiss()
    }

}











